package com.dongdongshop.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.dongdongshop.config.AlidyConfig;
import com.dongdongshop.service.SmsService;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    private AsyncClient client;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void sendPhoneMessage(String phoneNum) {
        String s = RandomUtil.randomNumbers(6);
        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("东科创想")
                .templateCode("SMS_162522027")
                .templateParam("{\"sms_code\":\""+s+"\"}")
                .phoneNumbers(phoneNum)
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(new Gson().toJson(resp));
        //如果操作成功将验证码存入redis并设置过期时间
        redisTemplate.boundValueOps(phoneNum).set(s);
        //设置过期时间30分钟
        redisTemplate.expire(phoneNum,30, TimeUnit.MINUTES);
    }

}



